# cython: language_level=3
import json
from typing import Annotated

from fastapi import Header, HTTPException, Request, Depends

from app.middlewares.redis import get_redis
from app.router.token import check_authorization
from common.log import get_logger

logger = get_logger('auth')


async def verify_token(
        request: Request,
        authorization: Annotated[str | None, Header()] = None,
        redis=Depends(get_redis),
):
    path: str = request.get("path")
    logger.info(path)
    if path.startswith("/api/getToken") or path.startswith("/api/device/updateResourceData"):
        return None

    if not authorization:
        raise HTTPException(status_code=401, detail={"error": "Unauthorized"})

    try:
        authorization_json = json.loads(authorization)
        app_id = authorization_json.get("appId")
        token = authorization_json.get("token")
        sign = authorization_json.get("sign")

        if not check_authorization(app_id, token, sign, redis):
            raise HTTPException(status_code=401, detail={"error": "Unauthorized"})

    except json.JSONDecodeError:
        raise HTTPException(
            status_code=400, detail={"error": "Invalid authorization format"}
        )
